package v2

import (
	"fmt"
	"log"
	v4 "mindonmap/api/v4"
	"mindonmap/pkgs/e"
	"mindonmap/pkgs/util"
	"mindonmap/validation"
	"net/http"

	"github.com/gin-gonic/gin"
	"time"
)

type MindImage struct {
	Acid   string `json:"acid"`
	Mindid string `json:"mindid"`
}

func UploadDocument(c *gin.Context) {
	mindid := c.PostForm("mindid")
	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	strUserid := fmt.Sprintf("%d", Userid)
	var JsondataInfo = &MindImage{
		Acid:   strUserid,
		Mindid: mindid,
	}
	valid := validation.Validation{}
	valid.Required(JsondataInfo.Mindid, "mindid").Message("不能为空")

	code := e.SUCCESS
	data := make(map[string]interface{})
	if !valid.HasErrors() {

		fileHeader, _ := c.FormFile("file")
		f, _ := fileHeader.Open()
		var size int64 = fileHeader.Size
		buffer := make([]byte, size)
		f.Read(buffer)

		now := time.Now()
		filepath := now.Format("2006-01-02")
		Filename := filepath + "/" + JsondataInfo.Acid + "/" + JsondataInfo.Mindid + "/" + fileHeader.Filename

		data["url"] = util.WriteFileR2_image(Filename, size, buffer)

	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}
